package com.zdf.license.core.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zdf.license.core.model.LicenseExtraParam;
import lombok.extern.log4j.Log4j;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Log4j
public class Base64Utils {
    final static Base64.Encoder encoder = Base64.getEncoder();
    final static Base64.Decoder decoder = Base64.getDecoder();

    /**
     * 给字符串加密
     */
    public static String encode(String text) {
        return encoder.encodeToString(text.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 将加密后的字符串进行解密
     */
    public static String decode(String encodedText) {
        return new String(decoder.decode(encodedText), StandardCharsets.UTF_8);
    }

    public static String encodeLicenseExtraParam(LicenseExtraParam licenseExtra) {
        return encode(JSONObject.toJSONString(licenseExtra));
    }

    public static LicenseExtraParam decodeLicenseExtraParam(String licenseExtra) {
        String decode = Base64Utils.decode(licenseExtra);
        JSONObject userJson = JSONObject.parseObject(decode);
        return JSON.toJavaObject(userJson,LicenseExtraParam.class);
    }

    /**
     * 获取文件的MD5
     *
     * @param filePath 文件路径
     * @return MD5
     */
    public static String getMd5(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return "";
        }
        try (FileInputStream is = new FileInputStream(file)) {
            return DigestUtils.md5Hex(is);
        } catch (Exception e) {
            log.info(filePath + " MD5生成失败，原因:" + e.getMessage());
            return "";
        }
    }
}
